<template>
  <div>
    <div class="card" style="margin-bottom: 10px;">
      <el-input prefix-icon="Search" style="width: 300px; margin-right: 10px" v-model="data.name"
                placeholder="请输入商品名称查询"></el-input>
      <el-button type="primary" plain round @click="load">查询</el-button>
      <el-button type="info" plain round style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 10px">
      <div style="margin-bottom: 10px">
        <el-button type="primary" plain round @click="handleAdd">新增</el-button>
      </div>
      <el-table :data="data.tableData" style="width: 100%">
        <el-table-column prop="id" label="序号" width="70"/>
        <el-table-column prop="img" label="商品图片">
          <template v-slot="scope">
            <el-image style="width: 60px; height: 60px; border-radius: 10px" :src="scope.row.img"
                      :preview-src-list="[scope.row.img]" preview-teleported/>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称"/>
        <el-table-column label="商品介绍">
          <template #default="scope">
            <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
              <el-button
                  style="background-color: #9b59b6; border-color: #9b59b6; color: white; border-radius: 5px;"
                  @click="viewIntroduction(scope.row.introduction)"
              >
                点击查看
              </el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="price" label="商品价格"/>
        <el-table-column prop="categoryName" label="商品分类"/>
        <el-table-column prop="supplierName" label="供货商"/>
        <el-table-column prop="count" label="商品库存"/>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <!-- 编辑和删除按钮 -->
            <el-button type="primary" :icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" :icon="Delete" circle @click="dele(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card" v-if="data.total">
      <el-pagination @current-change="changePage" background layout="prev, pager, next" :page-size="data.pageSize"
                     v-model:current-page="data.pageNum" :total="data.total"/>
    </div>

    <!-- 商品信息对话框 -->
    <el-dialog width="80%" v-model="data.formVisible" title="商品信息" destroy-on-close>
      <el-form :model="data.form" ref="formRef" :rules="rules" label-width="100px" label-position="right"
               style="display: flex; height: 350px; overflow: hidden;">
        <div style="width: 600px">
          <el-form-item label="商品图片">
            <el-upload
                class="upload-demo"
                :action="'http://localhost:9090/files/upload'"
                list-type="picture"
                :on-success="handleFileUpload"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="data.form.name" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input v-model="data.form.price" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="商品分类" prop="categoryId">
            <el-select v-model="data.form.categoryId" placeholder="请选择商品分类" style="width: 100%">
              <el-option v-for="item in data.categoryData" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="供货商" prop="supplierId">
            <el-select v-model="data.form.supplierId" placeholder="请选择供货商" style="width: 100%">
              <el-option v-for="item in data.supplierData" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="商品库存" prop="count">
            <el-input v-model="data.form.count" autocomplete="off"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="商品介绍" prop="introduction">
            <div style="border: 1px solid #ccc">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
              />
              <Editor
                  style="height: 200px; overflow-y: hidden;"
                  v-model="valueHtml"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 商品详情对话框 -->
    <el-dialog v-model="data.introDialogVisible" width="50%">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>商品详情</span>
          </div>
        </template>
        <div class="intro-content">
          <div v-if="data.currentIntroductionImg" class="intro-image">
            <el-image
                :src="data.currentIntroductionImg"
                fit="contain"
                style="max-width: 100%; border-radius: 10px; margin-bottom: 20px;"
            ></el-image>
          </div>
          <div v-html="data.currentIntroduction" class="intro-text"></div>
        </div>
      </el-card>
      <template #footer>
        <el-button @click="data.introDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

  </div>
</template>


<script setup>
import {reactive, onBeforeUnmount, ref, shallowRef, onMounted} from "vue"
import request from "@/utils/request";
import {Delete, Edit} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css

// 编辑器实例
const editorRef = shallowRef()
const valueHtml = ref('<p>hello</p>')

onMounted(() => {
  setTimeout(() => {
    valueHtml.value = data.form.introduction
  }, 1500)
})

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: 'http://localhost:9090/files/wang/upload',
      fieldName: 'file',
      customInsert(res, insertFn) {
        if (res.errno !== 0 || !res.data || !Array.isArray(res.data) || !res.data[0].url) return;
        const imageUrl = res.data[0].url;
        insertFn(imageUrl);
      }
    }
  }
}

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor) editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor
}

const data = reactive({
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 5,
  total: 0,
  formVisible: false,
  form: {
    introduction: ''
  },
  introDialogVisible: false,
  currentIntroduction: '',
  categoryData: [],
  supplierData: []
})

const rules = reactive({
  name: [
    {required: true, message: '请输入商品名称', trigger: 'blur'},
  ],
  price: [
    {required: true, message: '请输入商品价格', trigger: 'blur'},
  ]
})

const formRef = ref()

const handleAdd = () => {
  data.form = {}
  valueHtml.value = ''
  data.formVisible = true
}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  valueHtml.value = row.introduction
  data.formVisible = true
}

const handleFileUpload = (res) => {
  data.form.img = res.data
}

const loadCategory = () => {
  request.get('/category/selectAll').then(res => {
    if (res.code === '200') {
      data.categoryData = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const loadSupplier = () => {
  request.get('/supplier/selectAll').then(res => {
    if (res.code === '200') {
      data.supplierData = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const update = () => {
  data.form.introduction = valueHtml.value
  request.put('/goods/update', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('更新成功')
      data.formVisible = false
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const add = () => {
  data.form.introduction = valueHtml.value
  request.post('/goods/add', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('新增成功')
      data.formVisible = false
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      data.form.introduction = valueHtml.value
      data.form.id ? update() : add()
    }
  })
}

const dele = (id) => {
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(() => {
    request.delete('/goods/deleteById/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {
  })
}

const viewIntroduction = (introduction) => {
  data.currentIntroduction = introduction || '暂无商品介绍'
  data.introDialogVisible = true
}

const load = () => {
  request.get('/goods/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || []
      data.total = res.data?.total
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const changePage = (pageNum) => {
  data.pageNum = pageNum
  load()
}

const reset = () => {
  data.name = null
  load()
}

loadCategory()
loadSupplier()
load()

</script>

<style scoped>
.card-header {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  text-align: center;
  padding: 5px 0;
  border-bottom: 1px solid #ebeef5;
}

.intro-content {
  padding: 20px;
  font-size: 16px;
  line-height: 1.8;
  color: #666;
}

.intro-image {
  text-align: center;
}

.intro-text {
  margin-top: 20px;
}

</style>